package com.shamine.kuaiqiao.blink.gallery

import android.Manifest
import android.app.*
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import android.view.Menu
import android.view.MenuItem
import android.view.View
import cn.bmob.v3.BmobUser
import com.chad.library.adapter.base.BaseQuickAdapter
import com.shamine.kuaiqiao.blink.data.Gallery
import com.shamine.kuaiqiao.blink.event.EventGalleryDeleted
import com.shamine.kuaiqiao.blink.event.EventUserGalleries
import com.theartofdev.edmodo.cropper.CropImage
import com.theartofdev.edmodo.cropper.CropImageView
import dmax.dialog.SpotsDialog
import kotlinx.android.synthetic.main.activity_gallery.*
import kotlinx.android.synthetic.main.content_gallery.*
import kotlinx.android.synthetic.main.layout.*
import com.shamine.kuaiqiao.blink.R
import com.shamine.kuaiqiao.blink.basic.BaseActivity
import com.shamine.kuaiqiao.blink.detail.DetailActivity
import com.shamine.kuaiqiao.blink.events.*
import com.shamine.kuaiqiao.blink.gallery.create.AddGallery
import com.shamine.kuaiqiao.blink.receiver.BlinkReceiver
import com.shamine.kuaiqiao.blink.welcome.WelcomeActivity
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import java.util.*

class GalleryActivity : BaseActivity(),View.OnClickListener {

    private lateinit var adapter: GalleryAdapter
    private lateinit var manager: LinearLayoutManager
    private lateinit var worker: Worker
    private lateinit var galleries: MutableList<Gallery>
    private lateinit var dialog: Dialog
    //new photo gallery
    private var position = 0

    companion object {
        val ACTION = "com.shamine.kuaiqiao.action_reminder"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_gallery)
        EventBus.getDefault().register(this)
        setSupportActionBar(toolbar)
        supportActionBar?.title = getString(R.string.label_gallery)
        dialog = SpotsDialog(this,R.style.DialogWait)
        worker = Worker(this)
        initAdapter()
        setAlarm()
        if (isConnected()) getGalleries() else error.text = getString(R.string.status_device_offline)
    }

    private fun setAlarm() {
        val manager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
        //间隔时间12个小时提醒一次
        val interval = 1000L*60*60*12
        val calendar = Calendar.getInstance()
        val hour = calendar.get(Calendar.HOUR_OF_DAY)
        val day = calendar.get(Calendar.DATE)
        val month = calendar.get(Calendar.MONTH)
        val year = calendar.get(Calendar.YEAR)
        //设置到第二天
        if (hour >= 18){
            when(month){
                1,3,5,7,8,10,12 -> {
                    if (day == 31) {
                        calendar.roll(Calendar.MONTH,true)
                        calendar.set(Calendar.DATE,1)
                        calendar.set(Calendar.HOUR_OF_DAY,6)
                    }
                }
                4,6,9,11 -> {
                    if (day == 30) {
                        calendar.roll(Calendar.MONTH,true)
                        calendar.set(Calendar.DATE,1)
                        calendar.set(Calendar.HOUR_OF_DAY,6)
                    }
                }
                2 -> {
                    if (year % 4 == 0 && day == 29){
                        calendar.roll(Calendar.MONTH,true)
                        calendar.set(Calendar.DATE,1)
                        calendar.set(Calendar.HOUR_OF_DAY,6)
                    } else if ( day == 28) {
                        calendar.roll(Calendar.MONTH,true)
                        calendar.set(Calendar.DATE,1)
                        calendar.set(Calendar.HOUR_OF_DAY,6)
                    }
                }
            }
        }
        //设置到下午
        if (hour in 6 until 18) calendar.set(Calendar.HOUR_OF_DAY,18)
        if (hour in 0 until 6) calendar.set(Calendar.HOUR_OF_DAY,6)
        calendar.set(Calendar.MINUTE, 0)
        calendar.set(Calendar.SECOND,0)
        val intent = Intent(this, BlinkReceiver::class.java)
        intent.action = ACTION
        val pIntent = PendingIntent.getBroadcast(this,1228,intent,0)
        manager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.timeInMillis,interval,pIntent)
    }

    private fun getGalleries(){
        error.text = getString(R.string.status_getting_data)
        if (isConnected()) {
            worker.getGalleries()
        }else error.text = getString(R.string.status_device_offline)
    }

    /**
     * 初始化adapter
     */
    private fun initAdapter(){
        adapter = GalleryAdapter(this)
        adapter.onItemClickListener = BaseQuickAdapter.OnItemClickListener { _, _, position ->
            EventBus.getDefault().postSticky(EventGallery(DetailActivity::class.java,galleries[position]))
            goTo(DetailActivity::class.java,false)
        }
        adapter.onItemLongClickListener = BaseQuickAdapter.OnItemLongClickListener { _, _, position ->
            this@GalleryActivity.position = position
            CropImage.startPickImageActivity(this)
            true
        }


        adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN)
        manager = LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)
        list.hasFixedSize()
        list.layoutManager = manager
        list.adapter = adapter
    }

    override fun onClick(p0: View?) {
        when(p0?.id){
            //todo click to retry
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_gallery,menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when(item?.itemId){
            R.id.action_add -> goTo(AddGallery::class.java,false)
              //退出登陆
            R.id.action_sign_out ->{
                AlertDialog.Builder(this)
                        .setTitle(getString(R.string.sure_sign_out))
                        .setPositiveButton(getString(R.string.btn_ok)) { _, _ ->
                            BmobUser.logOut()
                            EventBus.getDefault().post(EventSignOut())
                        }
                        .setNegativeButton(getString(R.string.btn_cancel)){_, _ -> }
                        .show()
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) when(requestCode){
            CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE -> {
                val imageUri = CropImage.getPickImageResultUri(this, data)
                startCropping(imageUri)
            }
            CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE ->{
                val result = CropImage.getActivityResult(data)
                if (resultCode == RESULT_OK) {
                    //resultUri.path: /data/user/0/com.shamine.kuaiqiao.blink/cache/cropped1370004873.jpg
                    dialog.show()
                    worker.upload(result.uri.path,galleries[position])
                } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                    val error = result.error
                    toast(this,error.message.toString())
                }
            }
        }
    }

    //开始裁剪选择的图片
    private fun startCropping(imageUri: Uri) {
        CropImage.activity(imageUri)
                .setAspectRatio(9,16)
                .setCropShape(CropImageView.CropShape.RECTANGLE)
                .setAllowRotation(false)
                .setAutoZoomEnabled(true)
                .setMinCropResultSize(900,1600)
                .start(this)
    }

    /**
     * 删除相册结果
     */
    @Subscribe
    fun galleryDeleted(event: EventGalleryDeleted){
        dialog.dismiss()
        if (event.deleted){
            toast(this,getString(R.string.toast_success))
            worker.getGalleries()
        } else toast(this,getString(R.string.toast_fail)+event.msg)
    }

    /**
     * 获取相册成功
     */
    @Subscribe
    fun userGalleries(event: EventUserGalleries){
        if (event.done) {
            if (event.list.size == 0)
                error.text = getString(R.string.status_empty_gallery)
            else {
                error.visibility = View.GONE
                galleries = event.list
                adapter.setNewData(event.list)
            }
        } else {
            error.text = event.msg
        }
    }

    /**
     * 新增照片 结果
     */
    @Subscribe
    fun newGallery(event: EventAddGallery){
        worker.getGalleries()
    }

    /**
     * 新增照片 结果
     */
    @Subscribe
    fun photoUpload(event: EventPhotoUpload){
        if (dialog.isShowing) dialog.dismiss()
        worker.getGalleries()
    }

    /**
     * 删除照片 结果
     */
    @Subscribe
    fun photoDeleted(event: EventPhotoDeleted){
        worker.getGalleries()
    }

    @Subscribe
    override fun onSignOut(event: EventSignOut) {
        EventBus.getDefault().unregister(this)
        goTo(WelcomeActivity::class.java,true)
        finish()
    }

    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }
}
